# -*- encoding: utf-8 -*-
# k2000 parser
# http://85.221.21.34/k2000/k2post.sett_nsf/frmShowMailBySpecifiedDate?OpenForm&Date=20071004
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging
from datetime import datetime
from time import strptime
import jeje.parser
#import jeje
import re

class parser(jeje.parser.ejeje_parser):
    def parse_enkeltjournal(self, suppe, uri):
        #jeje.parser.ejeje_parser.__init__(self, suppe, postjournal_samling)
        logging.info('starter k2000-parser')
        #self.sett_info(suppe.)
        logging.debug('finner tittelposter i suppa')
        try:
            #_tittelposter = suppe.find('td', {'width':'690', 'valign':'top'}).find('table', {'width':'100%', 'border':'0', 'cellspacing':'0'}).findAll('tr', {'bgcolor':'#C0C0FF'})
            _tittelposter = suppe.findAll('tr', {'bgcolor':'#C0C0FF'})
            logging.debug('fant %d titler', len(_tittelposter))
        except AttributeError:
            return [] # ingen journalposter denne dagen
        for i, tp in enumerate(_tittelposter):
            logging.debug('arbeider med post #%d: %s', i, tp.a.string)
            post = self.legg_til_post()
            post.sett_tittel(unicode(tp.a.string))
            post.sett_offentlig(-1 != tp.a.find('/k2000/k2post.sett_nsf/viewAttachmentsMail'))
            verdier = {}
            while True:
                tp = tp.findNextSibling()
                if tp is None or tp in _tittelposter:
                    break #kommet til neste journlpost el. slutten på lista
                try: 
                    koler = [a.string for a in tp.findAll('b') if a]
                    for z in koler:
                        verdier[unicode(z.strip())] = unicode(z.next.string.strip())
                except AttributeError:
                    logging.debug('FEIL: %s' , tp)
                    post.sett_kommentar(unicode(tp.td.string))
                    continue
            for kol,verdi in verdier.iteritems():
                if kol == u'Sakstittel:':
                    post.sett_sakskompleks(verdi)
                elif kol == u'Arkivsaksnr.:':
                    _a, _d = verdi[:-2].split(' - ')
                    post.sett_arkivsaksnr(_a)
                    post.sett_dokumentnr(_d)
                    post.sett_retning(verdi[-1].upper())
                elif kol == u'Løpenr.:':
                    post.sett_refnr(verdi)
                elif kol == u'Fra/Til:':
                    post.sett_adressat(verdi)
                elif kol == u'Saksbehandler:':
                    if '(' in verdi:
                        start = verdi.find('(')
                        slutt = verdi.find(')')
                        person  = post.sett_saksbehandler(verdi[:start])
                        avdeling = person.sett_organisasjon(verdi[start:slutt])
                        avdeling.type = u'avdeling'
                        avdeling.moder_id = post.postjournal.organisasjon_id
                    else:
                        person = post.sett_saksbehandler(verdi)
                elif kol == u'Datert:':
                    post.sett_dokumentdato(datetime(*strptime(verdi, '%d.%m.%Y')[0:6]))
                elif kol == u'Gradering:':
                    post.sett_lovreferanse(verdi)
            post.kontroller_felter()
            
        return self.journalposter

if False:
    if None:
        if None:
            rad1 = tp.findNextSibling()
            post.sett_kommentar = unicode(rad1.td.string)
            rad2 = rad1.findNextSibling()
            print rad2
            _arkivsaksnr, refnr = [ x.next.next.strip() for x in rad2.findAll('b') ]
            post.sett_retning = _arkivsaksnr[-1].upper()
            arkivsaksnr, dokumentnr = _arkivsaksnr[:-2].split(' - ')
            logging.debug('arkivsaksnr: %s, refnr: %s', arkivsaksnr, refnr)
            post.sett_arkivsaksnr = unicode(arkivsaksnr)
            post.sett_refnr = unicode(refnr)
            post.sett_dokumentnr = unicode(dokumentnr)
            rad3 = rad2.findNextSibling()
            try:
                assert rad3.b.string.lower().strip() == 'fra/til:'
                post.sett_adressat(unicode(rad3.b.next.next))
                rad4 = rad3.findNextSibling()
            except AssertionError:
                logging.debug('Linjen med avsender/mottaker mangler, går rett videre')
                rad4 = rad3
            assert rad4.b.string.lower().strip() == 'saksbehandler:'
            post.sett_saksbehandler(unicode(rad4.b.next.next))
            rad5 = rad4.findNextSibling()
            assert rad5.b.string.lower().strip() == 'datert:'
            post.sett_dokumentdato = datetime(*strptime(rad5.b.next.next.strip(), '%d.%m.%Y')[0:6])
            post.sett_lovreferanse = unicode(rad5.find(text=re.compile('Unntatt')))
            #post.sett_retning(str(_type.span.next))
